package cc.rengu.redp.system.controller;

import cc.rengu.redp.base.authentication.UpmpJWTUtil;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.exception.RedisConnectException;
import cc.rengu.redp.common.properties.RedpProperties;
import cc.rengu.redp.common.redis.RedisService;
import cc.rengu.redp.common.utils.IPUtil;
import cc.rengu.redp.common.utils.SpringContextUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RestController
public class TokenController extends BaseController {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private RedisService redisService;

    private static final long EXPIRE_TIME = SpringContextUtil.getBean(RedpProperties.class).getShiro().getJwtTimeOut();

    @GetMapping(value = "/admin/getToken")
    public List getTokenByName(HttpServletRequest request) throws RedisConnectException {
        String ip = IPUtil.getIpAddr(request);
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String token;
        ArrayList list = Lists.newArrayList();
        for (int i = 0; i < 100; i++) {
            token = UpmpJWTUtil.encryptToken(UpmpJWTUtil.sign(user.getId(), String.valueOf(i)));
            list.add(token);
        }
        redisService.set(UpmpConstant.USER_TOKENS + user.getId() + StringPool.DOT + ip, JSON.toJSON(list).toString(), EXPIRE_TIME * 1000);
        return list;
    }
}
